package com.lxgzhw.student_manager02.controller;

import com.lxgzhw.student_manager02.domain.Result;
import com.lxgzhw.student_manager02.domain.Student;
import com.lxgzhw.student_manager02.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/edit")
    public String edit(Model model, Integer id) {
        Student student = studentService.get(id);
        model.addAttribute("student", student);
        return "studentEdit";
    }

    @GetMapping("/delete")
    public String delete(Integer id) {
        studentService.delete(id);
        return "redirect:/";
    }

    @PostMapping("/add")
    public String add(Student student) {
        if (studentService.add(student)) {
            return "redirect:/";
        } else {
            return "redirect:/studentAdd";
        }
    }

    @GetMapping("/listData")
    @ResponseBody
    public Result<Student> listData(Integer page, Integer limit) {
        if (page == null || page == 0) {
            page = 1;
        }
        if (limit == null || limit == 0) {
            limit = 10;
        }
        return studentService.page(page, limit);
    }
}
